import io
from enum import Enum
import time
import requests

""""
cgi命令，操控车载网络摄像头。
"""


class CameraCMD(Enum):
    CMD_PTZ_UP = 0  # 上
    CMD_PTZ_UP_STOP = 1  # 上停
    CMD_PTZ_DOWN = 2  # 下
    CMD_PTZ_DOWN_STOP = 3  # 下停
    CMD_PTZ_LEFT = 4  # 左
    CMD_PTZ_LEFT_STOP = 5  # 左停
    CMD_PTZ_RIGHT = 6  # 右
    CMD_PTZ_RIGHT_STO = 7  # 右停
    CMD_PTZ_CENTER = 25  # 自动巡航并居中
    CMD_PTZ_IRCUT_HIGH = 96  # 开Ir_Cut
    CMD_PTZ_IRCUT_LOW = 97  # 关Ir_Cut


def getIpcamStatus(ip: str, port=81, user='admin', pwd='888888'):
    """
    获取IP摄像头的状态
    :param ip:
    :param port:
    :param user:
    :param pwd:
    :return:
    """
    get_url_path = ''.join(['http://', ip, ':', str(port), '/get_status.cgi?user=', user, '&pwd=', pwd])
    r = requests.get(get_url_path)
    if r.status_code == 200:
        lr = r.content.decode('utf-8').replace('var ', '').split('\r\n')[:-1]
        dc = dict()
        for s in lr:
            k, v = s.split('=')
            dc[k] = v.replace(';', '').replace('"', '')
        return dc
    else:
        return r.status_code


def getIpcamParams(ip: str, port=81, user='admin', pwd='888888'):
    """
    获取IP摄像头的参数
    :param ip:
    :param port:
    :param user:
    :param pwd:
    :return:
    """
    get_url_path = ''.join(['http://', ip, ':', str(port), '/get_params.cgi?user=', user, '&pwd=', pwd])
    r = requests.get(get_url_path)
    if r.status_code == 200:
        lr = r.content.decode('utf-8').replace('var ', '').split('\r\n')[:-1]
        dc = dict()
        for s in lr:
            k, v = s.split('=')
            dc[k] = v.replace(';', '').replace('"', '')
        return dc
    else:
        return r.status_code


def getIpcamCameraParams(ip: str, port=81, user='admin', pwd='888888'):
    """
    获取IP摄像头的摄像参数
    :param ip:
    :param port:
    :param user:
    :param pwd:
    :return:
    """
    get_url_path = ''.join(['http://', ip, ':', str(port), '/get_camera_params.cgi?user=', user, '&pwd=', pwd])
    r = requests.get(get_url_path)
    if r.status_code == 200:
        lr = r.content.decode('utf-8').replace('var ', '').split('\r\n')[:-1]
        dc = dict()
        for s in lr:
            k, v = s.split('=')
            dc[k] = v.replace(';', '').replace('"', '')
        return dc
    else:
        return r.status_code


def getIpcamMisc(ip: str, port=81, user='admin', pwd='888888'):
    get_url_path = ''.join(['http://', ip, ':', str(port), '/get_misc.cgi?user=', user, '&pwd=', pwd])
    r = requests.get(get_url_path)
    if r.status_code == 200:
        lr = r.content.decode('utf-8').replace('var ', '').split('\r\n')[:-1]
        dc = dict()
        for s in lr:
            k, v = s.split('=')
            dc[k] = v.replace(';', '').replace('"', '')
        return dc
    else:
        return r.status_code


def getIpcamAlarmlog(ip: str, port=81, user='admin', pwd='888888'):
    get_url_path = ''.join(['http://', ip, ':', str(port), '/get_alarmlog.cgi?user=', user, '&pwd=', pwd])
    r = requests.get(get_url_path)
    if r.status_code == 200:
        lr = r.content.decode('utf-8').replace('var ', '').split('\r\n')[:-1]
        dc = dict()
        for s in lr:
            k, v = s.split('=')[:2]
            dc[k] = v.replace(';', '').replace('"', '')
        return dc
    else:
        return r.status_code


def getIpcamRecord(ip: str, port=81, user='admin', pwd='888888'):
    get_url_path = ''.join(['http://', ip, ':', str(port), '/get_record.cgi?user=', user, '&pwd=', pwd])
    r = requests.get(get_url_path)
    if r.status_code == 200:
        lr = r.content.decode('utf-8').replace('var ', '').split('\r\n')[:-1]
        dc = dict()
        for s in lr:
            k, v = s.split('=')[:2]
            dc[k] = v.replace(';', '').replace('"', '')
        return dc
    else:
        return r.status_code


def getIpcamRecordFile(ip: str, port=81, user='admin', pwd='888888'):
    get_url_path = ''.join(['http://', ip, ':', str(port), '/get_record_file.cgi?user=', user, '&pwd=', pwd])
    r = requests.get(get_url_path)
    if r.status_code == 200:
        lr = r.content.decode('utf-8').replace('var ', '').split('\r\n')[:-1]
        dc = dict()
        for s in lr:
            k, v = s.split('=')[:2]
            dc[k] = v.replace(';', '').replace('"', '')
        return dc
    else:
        return r.status_code


def getIpcamWifiScanResult(ip: str, port=81, user='admin', pwd='888888'):
    get_url_path = ''.join(['http://', ip, ':', str(port), '/get_wifi_scan_result.cgi?user=', user, '&pwd=', pwd])
    r = requests.get(get_url_path)
    if r.status_code == 200:
        lr = r.content.decode('utf-8').replace('var ', '').split('\r\n')[:-1]
        dc = dict()
        for s in lr:
            k, v = s.split('=')[:2]
            dc[k] = v.replace(';', '').replace('"', '')
        return dc
    else:
        return r.status_code


def getIpcamRTSP(ip: str, port=81, user='admin', pwd='888888'):
    get_url_path = ''.join(['http://', ip, ':', str(port), '/get_rtsp.cgi?user=', user, '&pwd=', pwd])
    r = requests.get(get_url_path)
    if r.status_code == 200:
        lr = r.content.decode('utf-8').replace('var ', '').split('\r\n')[:-1]
        dc = dict()
        for s in lr:
            k, v = s.split('=')[:2]
            dc[k] = v.replace(';', '').replace('"', '')
        return dc
    else:
        return r.status_code


def getIpcamSnapshot(ip: str, port=81, user='admin', pwd='888888', res='0'):
    import numpy as np
    from PIL import Image
    get_url_path = ''.join(['http://', ip, ':', str(port), '/snapshot.cgi?'])
    payload = {'user': user, 'pwd': pwd, 'res': res}
    head = {
        'User-Agent': 'Mozilla/5.0 (X11; Linux aarch64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/83.0.4103.61 Chrome/83.0.4103.61 Safari/537.36'}
    r = requests.get(get_url_path, params=payload)
    if r.status_code == 200:
        with io.BytesIO(r.content) as f:
            with Image.open(f) as img:
                # img.show()
                return np.array(img).reshape((360, 640, 3))  # rgb
    else:
        return np.zeros((360, 640, 3), dtype=np.uint8)


def IpcamReboot(ip: str, port=81, user='admin', pwd='888888'):
    get_url_path = ''.join(['http://', ip, ':', str(port), '/reboot.cgi?'])
    payload = {'user': user, 'pwd': pwd}
    r = requests.get(get_url_path, params=payload)
    if r.status_code == 200:
        print('摄像头重启中。。。')


def ptz_control(ip: str, command=1, onestep=1, port=81, user='admin', pwd='888888'):
    get_url_path = ''.join(['http://', ip, ':', str(port), '/decoder_control.cgi?'])
    payload = {'command': command, 'onestep': onestep, 'sit': 1, 'user': user, 'pwd': pwd}
    try:
        r = requests.get(get_url_path, params=payload)
        if r.status_code == 200:
            pass
    except Exception as e:
        import logging
        logging.exception(e)


def keyScan(cameraIP, k):
    if k == 'w':
        ptz_control(cameraIP, command=CameraCMD.CMD_PTZ_UP.value)
    elif k == 's':
        ptz_control(cameraIP, command=CameraCMD.CMD_PTZ_UP_STOP.value)
    elif k == 'x':
        ptz_control(cameraIP, command=CameraCMD.CMD_PTZ_DOWN.value)
    elif k == 'a':
        ptz_control(cameraIP, command=CameraCMD.CMD_PTZ_LEFT.value)
    elif k == 'd':
        ptz_control(cameraIP, command=CameraCMD.CMD_PTZ_RIGHT.value)

    elif k == 'c':
        ptz_control(cameraIP, command=CameraCMD.CMD_PTZ_CENTER.value)
        print("camera is reseting Need to wait one minute")
        i = 0
        while True:
            time.sleep(5)
            i += 1
            print("Already waiting：{} s / Still have to wait：{} s".format(i * 5, 60 - i * 5))
            if i > 11:
                break

    elif k == 'i':
        ptz_control(cameraIP, command=CameraCMD.CMD_PTZ_IRCUT_HIGH.value)

    elif k == 'o':
        ptz_control(cameraIP, command=CameraCMD.CMD_PTZ_IRCUT_LOW.value)

    elif k == "1":
        # 设置预设位1 向左
        ptz_control(cameraIP, command=0x30)
    elif k == '2':
        # 设置预设位2  默认
        ptz_control(cameraIP, command=0x32)
    elif k == '3':
        # 设置预设位3  向右
        ptz_control(cameraIP, command=0x34)
    elif k == "4":
        # 调用预设位1 向左
        ptz_control(cameraIP, command=0x31)
    elif k == '5':
        # 调用预设位2  默认
        ptz_control(cameraIP, command=0x33)
    elif k == '6':
        # 调用预设位3  向右
        ptz_control(cameraIP, command=0x35)


def setDefulatPresetPosition(camera_ip):
    keyScan(camera_ip, 'c')
    cmd = '2aaa15ddd3465'
    for key in cmd:
        keyScan(camera_ip, key)
        time.sleep(1)
        print("----please wait...")
    print("------set defulat preset position is success")
    for key in "6446645":
        keyScan(camera_ip, key)
        time.sleep(1)


def test():
    camera_ip = '192.168.16.100'
    # status = getIpcamStatus(camera_ip)
    # print(status)
    #
    # params = getIpcamParams(camera_ip)
    # print(params)
    #
    # params = getIpcamCameraParams(camera_ip)
    # print(params)
    #
    # params = getIpcamMisc(camera_ip)
    # print(params)
    #
    # params = getIpcamAlarmlog(camera_ip)
    # print(params)
    #
    # params = getIpcamRecord(camera_ip)
    # print(params)
    #
    # params = getIpcamRecordFile(camera_ip)
    # print(params)
    #
    # params = getIpcamWifiScanResult(camera_ip)
    # print(params)
    #
    # params = getIpcamWifiScanResult(camera_ip)
    # print(params)
    #
    # params = getIpcamRTSP(camera_ip)
    # print(params)
    #
    # params = getIpcamOnvif(camera_ip)
    # print(params)

    # ptz_control(camera_ip, command = 18, onestep = 1)

def test1():
    camera_ip = '192.168.16.100'
    parsing = getIpcamRTSP(camera_ip)
    print(parsing)
    #
    # params = getIpcamParams(camera_ip)
    # print(params)
    #
    # params = getIpcamCameraParams(camera_ip)
    # print(params)
    # keyScan(camera_ip, "w")
    # import time
    # time.sleep(3)
    # keyScan(camera_ip, "c")
    # print(getIpcamStatus(camera_ip))
    # image = getIpcamSnapshot(camera_ip)
    # image.show()

    # setDefulatPresetPosition(camera_ip)
    rgb = getIpcamSnapshot(camera_ip)
    import cv2
    cv2.imshow('rgb', rgb)
    cv2.waitKey(0)

if __name__ == '__main__':
    test()
